﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Frw.Windows.Services.Monitor;
using Frw.Protocols.Communications.Tcp;
using Test.Services.Commands;

namespace Test.ServiceMonitor
{
    public partial class Form1 : MonitorBase
    {
        Communicator<ServiceCommand> m_server = null;

        public Form1()
        {
            InitializeComponent();

            this.Icon = base.Icon;

            this.Load += new EventHandler(Form1_Load);
            
            this.Stopped += new EventHandler(Form1_Stopped);
        }

        void Form1_Load(object sender, EventArgs e)
        {
            SetupCommunicator();
        }

        void Form1_Stopped(object sender, EventArgs e)
        {
            m_server.Send(new ServiceCommand() { CommunicationBag = new Frw.Patterns.CommandPattern.Command<string>("ss", x => string.IsNullOrWhiteSpace(x)) });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SetupCommunicator();
        }

        private void SetupCommunicator()
        {
            if (m_server == null)
            {
                m_server = new Communicator<ServiceCommand>("MonitorGroup");

                m_server.DataRecieved += new EventHandler<Frw.EventArgs<ServiceCommand>>(m_server_OnDataRecieved);
                m_server.ActAsServer(); //("127.0.0.1", 7735);

                m_server.ActAsClient(); //("127.0.0.1", 7734);
            }
        }

        void m_server_OnDataRecieved(object sender, Frw.EventArgs<ServiceCommand> e)
        {
            Frw.CrossThreadOperation.Invoke(this.label1, () => UpdateText(e.TargetObject.CommunicationBag.ToString()));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            m_server.Send(new ServiceCommand() { CommunicationBag = "Esegui questo comando" });
        }

        private void UpdateText(string text)
        {
            this.label1.Text = text;
        }

    }
}
